package jt.classic.app.info;

import jt.classic.app.info.impl.AInfoDirectoryImpl;
import jt.classic.app.info.impl.AInfoImpl;
import jt.classic.app.info.impl.AInfoIssueImpl;

import jt.classic.system.AbstractSimpleManager;
import jt.classic.system.ISystem;
import jt.classic.system.ISystemException;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.group.IGroup;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;
import jt.classic.system.utils.SystemTool;
import jt.classic.system.wordbook.XWordbook;
import jt.classic.system.wordbook.XWordbookMain;
import jt.classic.system.wordbook.XWordbookQuery;

import net.sf.json.JSONArray;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;

import org.htmlparser.filters.TagNameFilter;

import org.htmlparser.tags.ImageTag;

import org.htmlparser.util.NodeList;

import org.limp.basework.Column;
import org.limp.basework.Table;
import org.limp.basework.analyzer.TableRegisterCenter;
import org.limp.basework.console.XSystemConfig;
import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.DataTrimmer;
import org.limp.mine.DateTrimmer;
import org.limp.mine.HTMLTool;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;
import org.limp.mine.annex.AnnexItem;
import org.limp.mine.annex.AttFileItem;

import java.io.File;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 内容信息管理者
 *
 * @author Bizkit
 *
 */
public class InfoManager extends AbstractSimpleManager {
    private static String context = (String) XSystemConfig.config().getProperty(XSystemConfig.XSYSTEM_CONTEXT);

    public InfoManager() {
        super();
    }

    public InfoManager(Connection conn) {
        super(conn);
    }

    /**
     * 根据信息ID获取信息
     *
     * @param id
     * @return
     */
    public AInfo getAInfoById(String id) {
        String sql = "SELECT * FROM APP_INFO WHERE IF_ID = " + id;
        Map info = this.trimmer.searchSingleData(sql);
        AInfo ainfo = null;

        if (info != null) {
            /* 信息发布人ID */
            String userid = (String) info.get("IF_USERID");

            UserManager manager = new UserManager(this.conn);

            IUser user = manager.getUserByLogID(userid);

            info.put("USER", user);

            info.put("IF_DOC", "0");

            /* 信息所属栏目 */
            String did = (String) info.get("ID_ID");

            AInfoDirectory direc = this.getAInfoDirectoryById(did);

            info.put("DIRECTORY", direc);

            /* 信息所属属专题 */
            AInfoDirectory subject = this.getAInfoSubjectById(did);
            info.put("SUBJECT", subject);

            /* 信息发布范围 */
            AInfoIssue issue = this.getAInfoIssueById(id);

            info.put("ISSUE", issue);

            /* 附件工具 */
            AnnexTool tool = new AnnexTool(this.conn);

            TableRegisterCenter center = TableRegisterCenter.getInstance();

            Table table = center.findTable("APP_INFO");

            /* 信息关联附件内容 */
            AnnexInfo[] annexinfos = tool.getAnnexs(id, table.getName());
            List list = new ArrayList();

            if ((annexinfos != null) && (annexinfos.length > 0)) {
                for (int i = 0; i < annexinfos.length; i++) {
                    list.add(new String[] {
                            
                        /* 附件ID,附件名称 */
                        annexinfos[i].getID(), annexinfos[i].getName()
                        });
                }
            }

            info.put("ANNEXS", list);

            ainfo = new AInfoImpl();

            ainfo.reload(info);
        }

        return ainfo;
    }

    /**
     * 信息发布
     *
     * @param id
     *            信息ID
     * @return AInfoIssue
     */
    public AInfoIssue getAInfoIssueById(String id) {
        String sql = "SELECT * FROM APP_INFO_ISSUE WHERE IS_OBJ_ID = " + id;
        List list = this.trimmer.searchMultiData(sql);

        AInfoIssue issue = new AInfoIssueImpl();

        if ((list != null) && !list.isEmpty()) {
            Map info = (Map) list.get(0);

            String areaid = "";

            String areaname = "";

            for (int i = 0; i < list.size(); i++) {
                Map temp = (Map) list.get(i);

                if (i == (list.size() - 1)) {
                    areaid += (String) temp.get("IS_AREAID");
                    areaname += (String) temp.get("IS_AREANAME");
                } else {
                    areaid += ((String) temp.get("IS_AREAID") + ",");
                    areaname += ((String) temp.get("IS_AREANAME") + ",");
                }
            }

            info.put("IS_AREAID", areaid);
            info.put("IS_AREANAME", areaname);

            issue.reload(info);
        }

        return issue;
    }

    /**
     * 获取信息目录
     *
     * @param id
     *            信息目录id
     * @return 信息目录key
     */
    public AInfoDirectory getAInfoDirectoryById(String id) {
        String sql = "SELECT * FROM APP_INFO_DIRECTORY WHERE ID_ID = " + id;
        Map info = this.trimmer.searchSingleData(sql);
        AInfoDirectory adirec = null;

        if ("0".equals(id)) {
            adirec = getRootDirectory();
        } else if (info != null) {
            adirec = new AInfoDirectoryImpl();

            String key = (String) info.get("ID_KEY");

            if (key.equals("")) {
                key = StringTool.getUniqueString();
            }

            byte[] labelpic = (byte[]) info.get("ID_LABELIMG");

            if ((labelpic != null) && (labelpic.length > 0)) {
                String tp = (String) info.get("ID_LABELIMGTYPE");
                String labelpicurl = SystemTool.createTempPic("label_" + key,
                        labelpic, tp);

                info.put("ID_LABELIMGURL", labelpicurl);
            } else {
                info.put("ID_LABELIMGURL",
                    context + "/app/info/images/default.gif");
            }

            byte[] titlepic = (byte[]) info.get("ID_TITLEIMG");

            if ((titlepic != null) && (titlepic.length > 0)) {
                String tp = (String) info.get("ID_TITLEIMGTYPE");
                String titlepicurl = SystemTool.createTempPic("title_" + key,
                        titlepic, tp);

                info.put("ID_TITLEIMGURL", titlepicurl);
            } else {
                info.put("ID_TITLEIMGURL",
                    context + "/app/info/images/default.gif");
            }

            boolean rnt = this.hasChildDirectory(id);
            info.put("HASCHILD", String.valueOf(rnt));

            String[] pathname = this.getDirectoryExtPath(id);
            info.put("EXT_DPATH", pathname[0]);
            info.put("EXT_DPATHTEXT", pathname[1]);

            adirec.reload(info);
        }

        return adirec;
    }

    /**
     * 获取信息目录
     *
     * @param id
     *            信息目录id
     * @return 信息目录key
     */
    public AInfoDirectory getAInfoDirectoryById(String realpath, String id) {
        String sql = "SELECT * FROM APP_INFO_DIRECTORY WHERE ID_ID = " + id;
        Map info = this.trimmer.searchSingleData(sql);
        AInfoDirectory adirec = null;

        if ("0".equals(id)) {
            adirec = getRootDirectory();
        } else if (info != null) {
            adirec = new AInfoDirectoryImpl();

            String key = (String) info.get("ID_KEY");

            if (key.equals("")) {
                key = StringTool.getUniqueString();
            }

            byte[] labelpic = (byte[]) info.get("ID_LABELIMG");

            if ((labelpic != null) && (labelpic.length > 0)) {
                String tp = (String) info.get("ID_TITLEIMGTYPE");
                String labelpicurl = SystemTool.createTempPic("label_" + key,
                        labelpic, tp);

                info.put("ID_LABELIMGURL", labelpicurl);
            } else {
                info.put("ID_LABELIMGURL",
                    context + "/app/info/images/default.gif");
            }

            byte[] titlepic = (byte[]) info.get("ID_TITLEIMG");

            if ((titlepic != null) && (titlepic.length > 0)) {
                String titlepicurl = SystemTool.createTempPic(realpath,
                        "title_" + key, titlepic);

                info.put("ID_TITLEIMGURL", titlepicurl);
            } else {
                info.put("ID_TITLEIMGURL",
                    context + "/app/info/images/default.gif");
            }

            boolean rnt = this.hasChildDirectory(id);
            info.put("HASCHILD", String.valueOf(rnt));

            String[] pathname = this.getDirectoryExtPath(id);
            info.put("EXT_DPATH", pathname[0]);
            info.put("EXT_DPATHTEXT", pathname[1]);

            adirec.reload(info);
        }

        return adirec;
    }

    /**
     * 获取信息目录
     *
     * @param key
     *            信息目录key
     * @return AInfoDirectory
     */
    public AInfoDirectory getAInfoDirectoryByKey(String key) {
        String sql = "SELECT ID_ID FROM APP_INFO_DIRECTORY WHERE ID_KEY = '" +
            key + "'";
        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            String id = (String) info.get("ID_ID");
            AInfoDirectory adirec = this.getAInfoDirectoryById(id);

            return adirec;
        }

        return null;
    }

    /**
     * 获取信息目录
     *
     * @param key
     *            信息目录key
     * @return AInfoDirectory
     */
    public AInfoDirectory getAInfoDirectoryByKey(String realpath, String key) {
        String sql = "SELECT ID_ID FROM APP_INFO_DIRECTORY WHERE ID_KEY = '" +
            key + "'";
        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            String id = (String) info.get("ID_ID");
            AInfoDirectory adirec = this.getAInfoDirectoryById(realpath, id);

            return adirec;
        }

        return null;
    }

    /**
     * 是否有子目录类别
     *
     * @param id
     *            父目录类别ID
     * @return boolean
     */
    public boolean hasChildDirectory(String id) {
        String sql = "SELECT * FROM APP_INFO_DIRECTORY WHERE ID_PARENT = " +
            id;

        return this.trimmer.haveMoreData(sql);
    }

    /**
     * 目录中是否存在信息
     *
     * @param id
     *            目录ID
     * @return boolean
     */
    public boolean hasChildInfoDirectory(String id) {
        String sql = "SELECT * FROM APP_INFO WHERE ID_ID = " + id;

        return this.trimmer.haveMoreData(sql);
    }

    /**
     * 子目录列表
     *
     * @param id
     * @return List
     */
    public List getChildDirectory(String id) {
        String sql = "SELECT * FROM APP_INFO_DIRECTORY WHERE ID_PARENT = " +
            id + " ORDER BY ID_ORDER";

        List list = this.trimmer.searchMultiData(sql);

        for (int i = 0; i < list.size(); i++) {
            Map temp = (Map) list.get(i);

            String _id = (String) temp.get("ID_ID");

            AInfoDirectory direc = this.getAInfoDirectoryById(_id);

            list.set(i, direc);
        }

        return list;
    }

    /**
     * 专题栏目/选择树
     *
     * @param id
     * @param showinfo
     * @param select
     * @return
     */
    public String getAInfoDirectoryTree(String id, IUser user) {
        PurviewManager pmanager = new PurviewManager(conn);

        String result = "{}";

        boolean hide = pmanager.purview4hide(id, "directory", user);

        if (hide) {
            // do nothing
        } else {
            AInfoDirectory adirec = this.getAInfoDirectoryById(id);

            int purview = pmanager.purview(id, "directory", user);

            if (adirec.isroot()) {
                ADJsonBean root = new ADJsonBean();
                root.setId(adirec.id());
                root.setText(adirec.iname());
                root.setMemo(adirec.imemo());
                root.setPid(adirec.iparentid());
                root.setIsroot(adirec.isroot());
                root.setPurview(purview);

                if (adirec.isroot()) {
                    root.setIconCls("icon-root");
                }

                List jsonList = new ArrayList();

                jsonList.add(root);

                List childrenList = new ArrayList();

                root.setChildren(childrenList);

                initDirectoryTreeScript(root, user, pmanager);

                JSONArray jsonArray = JSONArray.fromObject(jsonList);

                result = jsonArray.toString();
            } else if (user.id().equals(adirec.iuserid()) || (purview > -1)) {
                ADJsonBeanCK root = new ADJsonBeanCK();
                root.setId(adirec.id());
                root.setText(adirec.iname());
                root.setMemo(adirec.imemo());
                root.setPid(adirec.iparentid());
                root.setIsroot(adirec.isroot());
                root.setPurview(purview);
                root.setChecked(false);

                if (adirec.isroot()) {
                    root.setIconCls("icon-root");
                }

                List jsonList = new ArrayList();

                jsonList.add(root);

                List childrenList = new ArrayList();

                root.setChildren(childrenList);

                initDirectoryTreeScript(root, user, pmanager);

                JSONArray jsonArray = JSONArray.fromObject(jsonList);

                result = jsonArray.toString();
            }
        }

        return result;
    }

    /**
     * 主题管理树
     *
     * @param id
     * @param showinfo
     * @param select
     * @return String
     */
    public String getAInfoThemeTree(String id) {
        AInfoDirectory adirec = this.getAInfoDirectoryById(id);

        ADJsonBean root = new ADJsonBean();
        root.setId(adirec.id());
        root.setText(adirec.iname());
        root.setMemo(adirec.imemo());
        root.setPid(adirec.iparentid());
        root.setIsroot(adirec.isroot());

        if (adirec.isroot()) {
            root.setIconCls("icon-root");
        }

        List jsonList = new ArrayList();

        jsonList.add(root);

        List childrenList = new ArrayList();

        root.setChildren(childrenList);

        initThemeTreeScript(root);

        JSONArray jsonArray = JSONArray.fromObject(jsonList);

        return jsonArray.toString();
    }

    /**
     * 信息目录维护(专题/栏目维护)
     *
     * @param id
     * @param showinfo
     * @param select
     * @return
     */
    public String getAInfoDirectoryTree4manager(String id, IUser user) {
        PurviewManager pmanager = new PurviewManager(conn);

        String result = "{}";

        boolean hide = pmanager.purview4hide(id, "directory", user);

        if (hide) {
            // do nothing
        } else {
            AInfoDirectory adirec = this.getAInfoDirectoryById(id);

            int purview = pmanager.purview(id, "directory", user);

            if (adirec.isroot() || user.id().equals(adirec.iuserid()) ||
                    (purview > -1)) {
                if (user.id().equals(adirec.iuserid())) {
                    purview = 1;
                }

                ADJsonBean root = new ADJsonBean();
                root.setId(adirec.id());
                root.setText(adirec.iname());
                root.setMemo(adirec.imemo());
                root.setPid(adirec.iparentid());
                root.setIsroot(adirec.isroot());
                root.setPurview(purview);

                if (adirec.isroot()) {
                    root.setIconCls("icon-root");
                }

                List jsonList = new ArrayList();

                jsonList.add(root);

                List childrenList = new ArrayList();

                root.setChildren(childrenList);

                initDirectoryTreeScript4manager(root, user, pmanager);

                JSONArray jsonArray = JSONArray.fromObject(jsonList);

                result = jsonArray.toString();
            }
        }

        return result;
    }

    /**
     * 专题栏目树(授权)
     *
     * @param id
     * @param showinfo
     * @param select
     * @return
     */
    public String getAInfoDirectoryTree4purview(String id, boolean showinfo,
        boolean select) {
        String context = (String) XSystemConfig.config().getProperty(XSystemConfig.XSYSTEM_CONTEXT);

        AInfoDirectory adirec = this.getAInfoDirectoryById(id);

        StringBuffer script = new StringBuffer();

        if (adirec != null) {
            String url = select ? ""
                                : (context +
                "/system/purview.do?method=purview&oid=" + id +
                "&otype=directory&otable=APP_INFO_DIRECTORY&type=purview4user");

            if (getRootDirectory().id().equals(id)) {
                url = "";
            }

            script.append("d.add('g" + adirec.id() + "',-1,'" + adirec.iname() +
                "','" + url + "','" + adirec.imemo() + "','folder');\n");

            initDirectory4purviewTreeScript(adirec.id(), context, script,
                showinfo, select);
        }

        return script.toString();
    }

    /**
     * 信息发布目录�?
     *
     * @param id
     * @param showinfo
     * @param select
     * @return
     */
    public String getAInfoDirectoryTree4Issue(String id, boolean showinfo,
        boolean select, IUser user) {
        String context = (String) XSystemConfig.config().getProperty(XSystemConfig.XSYSTEM_CONTEXT);

        AInfoDirectory adirec = this.getAInfoDirectoryById(id);

        PurviewManager pmanager = new PurviewManager(conn);
        StringBuffer script = new StringBuffer();

        if (adirec.isroot() || pmanager.purview4read(id, "directory", user)) {
            String url = select ? ""
                                : (context +
                "/app/info.do?method=issuebydirectory&id=" + id);

            script.append("d.add('g" + adirec.id() + "',-1,'" + adirec.iname() +
                "','" + url + "','" + adirec.imemo() + "','folder');\n");

            initDirectory4IssueTreeScript(adirec.id(), context, script,
                showinfo, select, user, pmanager);
        }

        return script.toString();
    }

    /**
     * 初始化专题栏目树
     *
     * @param root
     */
    private void initThemeTreeScript(ADJsonBean root) {
        List list = this.getChildDirectory(root.getId());

        List myList = root.getChildren();

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                AInfoDirectory temp = (AInfoDirectory) list.get(i);
                ADJsonBean adbean = new ADJsonBean();
                adbean.setId(temp.id());
                adbean.setText(temp.iname());
                adbean.setMemo(temp.imemo());
                adbean.setPid(temp.iparentid());
                adbean.setIsroot(false);

                if (root.isIsroot()) {
                    adbean.setIconCls("icon-theme");
                }

                List childrenList = new ArrayList();

                adbean.setChildren(childrenList);

                if (this.hasChildDirectory(adbean.getId())) {
                    initThemeTreeScript(adbean);
                }

                myList.add(adbean);
            }
        }
    }

    private void initDirectoryTreeScript(ADJsonBean root, IUser user,
        PurviewManager pmanager) {
        List list = this.getChildDirectory(root.getId());

        List myList = root.getChildren();

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                AInfoDirectory temp = (AInfoDirectory) list.get(i);

                boolean hide = pmanager.purview4hide(temp.id(), "directory",
                        user);

                if (hide) {
                    // do nothing
                } else {
                    int purview = pmanager.purview(temp.id(), "directory", user);

                    if (user.id().equals(temp.iuserid()) || (purview > -1)) {
                        ADJsonBeanCK adbean = new ADJsonBeanCK();
                        adbean.setId(temp.id());
                        adbean.setText(temp.iname());
                        adbean.setMemo(temp.imemo());
                        adbean.setPid(temp.iparentid());
                        adbean.setIsroot(false);
                        adbean.setPurview(purview);
                        adbean.setChecked(false);

                        if (root.isIsroot()) {
                            adbean.setIconCls("icon-theme");
                        }

                        List childrenList = new ArrayList();

                        adbean.setChildren(childrenList);

                        if (this.hasChildDirectory(adbean.getId())) {
                            initDirectoryTreeScript(adbean, user, pmanager);
                        }

                        myList.add(adbean);
                    }
                }
            }
        }
    }

    private void initDirectoryTreeScript4manager(ADJsonBean root, IUser user,
        PurviewManager pmanager) {
        List list = this.getChildDirectory(root.getId());

        List myList = root.getChildren();

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                AInfoDirectory temp = (AInfoDirectory) list.get(i);

                boolean hide = pmanager.purview4hide(temp.id(), "directory",
                        user);

                if (hide) {
                    // do nothing
                } else {
                    int purview = pmanager.purview(temp.id(), "directory", user);

                    if (user.id().equals(temp.iuserid()) || (purview > -1)) {
                        if (user.id().equals(temp.iuserid())) {
                            purview = 1;
                        }

                        ADJsonBean adbean = new ADJsonBean();
                        adbean.setId(temp.id());
                        adbean.setText(temp.iname());
                        adbean.setMemo(temp.imemo());
                        adbean.setPid(temp.iparentid());
                        adbean.setIsroot(false);
                        adbean.setPurview(purview);

                        if (root.isIsroot()) {
                            adbean.setIconCls("icon-theme");
                        }

                        List childrenList = new ArrayList();

                        adbean.setChildren(childrenList);

                        if (this.hasChildDirectory(adbean.getId())) {
                            initDirectoryTreeScript4manager(adbean, user,
                                pmanager);
                        }

                        myList.add(adbean);
                    }
                }
            }
        }
    }

    private void initDirectory4purviewTreeScript(String id, String context,
        StringBuffer script, boolean showuser, boolean select) {
        List list = this.getChildDirectory(id);

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                AInfoDirectory temp = (AInfoDirectory) list.get(i);
                String _id = temp.id();
                String _name = temp.iname();
                String _intro = temp.imemo();

                String _url = select ? ""
                                     : (context +
                    "/system/purview.do?method=purview&oid=" + _id +
                    "&otype=directory&otable=APP_INFO_DIRECTORY&type=purview4user");

                script.append("d.add('g" + _id + "','g" + id + "','" + _name +
                    "','" + _url + "','" + _intro + "','folder');\n");

                if (showuser) {
                    /*
                     * List users = this.findUserInGroup(_id);
                     *
                     * for (int j = 0; j < users.size(); j++) { IUser user =
                     * (IUser) users.get(j); script.append("d.add('u" +
                     * user.id() + "','g" + _id + "','" + user.iname() +
                     * "','','" + user.ijob() + "','file');\n"); }
                     */
                }

                if (this.hasChildDirectory(_id)) {
                    initDirectory4purviewTreeScript(_id, context, script,
                        showuser, select);
                }
            }
        }
    }

    private void initDirectory4IssueTreeScript(String id, String context,
        StringBuffer script, boolean showuser, boolean select, IUser user,
        PurviewManager pmanager) {
        List list = this.getChildDirectory(id);

        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                AInfoDirectory temp = (AInfoDirectory) list.get(i);
                String _id = temp.id();
                String _name = temp.iname();
                String _intro = temp.imemo();

                if (pmanager.purview4read(_id, "directory", user)) {
                    String _url = select ? ""
                                         : (context +
                        "/app/info.do?method=issuebydirectory&id=" + _id);

                    script.append("d.add('g" + _id + "','g" + id + "','" +
                        _name + "','" + _url + "','" + _intro +
                        "','folder');\n");

                    if (showuser) {
                        /*
                         * List users = this.findUserInGroup(_id);
                         *
                         * for (int j = 0; j < users.size(); j++) { IUser user =
                         * (IUser) users.get(j); script.append("d.add('u" +
                         * user.id() + "','g" + _id + "','" + user.iname() +
                         * "','','" + user.ijob() + "','file');\n"); }
                         */
                    }

                    if (this.hasChildDirectory(_id)) {
                        initDirectory4IssueTreeScript(_id, context, script,
                            showuser, select, user, pmanager);
                    }
                }
            }
        }
    }

    /**
     * 预览记录
     *
     * @param id
     *            信息ID
     * @param userid
     *            用户ID
     * @param name
     *            用户名称
     * @param ip
     *            查看IP
     */
    public void trace(String id, IUser user, String ip) {
        String sql = "SELECT * FROM APP_INFO_RECEIPT WHERE AF_ID = " + id +
            " AND USER_ID = " + user.id();

        if (this.trimmer.haveMoreData(sql)) {
            sql = "UPDATE APP_INFO_RECEIPT SET RTIME = '" +
                DateTrimmer.getYMDHMS() + "',RIP = '" + ip +
                "' WHERE AF_ID = " + id + " AND USER_ID = " + user.id();
        } else {
            sql = "INSERT INTO APP_INFO_RECEIPT (AF_ID,USER_ID,USER_NAME,RTIME,RIP,GROUP_ID,GROUP_NAME) VALUES (" +
                id + "," + user.id() + ",'" + user.iname() + "'," +
                DateTrimmer.getYMDHMS() + ",'" + ip + "'," +
                ((user.igroup() != null) ? user.igroup().id() : "0") + ",'" +
                ((user.igroup() != null) ? user.igroup().iname() : "") + "')";
        }

        this.trimmer.execute(sql);
    }

    /**
     * 预览记录列表
     *
     * @param id
     *            信息ID
     * @return List
     */
    public List getTrace(String id) {
        String sql = "SELECT * FROM APP_INFO_RECEIPT WHERE AF_ID = " + id +
            " ORDER BY RTIME DESC";

        return this.trimmer.searchMultiData(sql);
    }

    public String[] getDirectoryExtPath(String id) {
        String path = null;
        String name = "";

        if (id.equals("0")) {
            path = "/-1/0";
        } else {
            String sql =
                "SELECT ID_PARENT,ID_NAME FROM APP_INFO_DIRECTORY WHERE ID_ID = " +
                id;

            Map info = this.trimmer.searchSingleData(sql);

            if (info != null) {
                String pid = (String) info.get("ID_PARENT");
                String dname = (String) info.get("ID_NAME");

                StringBuffer pathBuffer = new StringBuffer();
                StringBuffer nameBuffer = new StringBuffer();

                pathBuffer.append(id);
                nameBuffer.append(dname);

                initDirectoryExtPath(pid, pathBuffer, nameBuffer);

                String[] pathstr = pathBuffer.toString().split("/");

                int count = pathstr.length - 1;

                String result = "";

                while (count > -1) {
                    if (count == (pathstr.length - 1)) {
                        result += pathstr[count];
                    } else {
                        result += ("/" + pathstr[count]);
                    }

                    count--;
                }

                path = "/-1/0/" + result;

                String[] namestr = nameBuffer.toString().split("/");

                int count1 = namestr.length - 1;

                String result1 = "";

                while (count1 > -1) {
                    if (count1 == (namestr.length - 1)) {
                        result1 += namestr[count1];
                    } else {
                        result1 += ("/" + namestr[count1]);
                    }

                    count1--;
                }

                name = result1;
            } else {
                path = "/-1/0";
            }
        }

        return new String[] { path, name };
    }

    private void initDirectoryExtPath(String id, StringBuffer path,
        StringBuffer nameBuffer) {
        if (!"0".equals(id)) {
            String sql =
                "SELECT ID_PARENT,ID_NAME FROM APP_INFO_DIRECTORY WHERE ID_ID = " +
                id;

            Map info = this.trimmer.searchSingleData(sql);

            if (info != null) {
                String pid = (String) info.get("ID_PARENT");
                String dname = (String) info.get("ID_NAME");

                nameBuffer.append("/" + dname);

                path.append("/" + id);

                initDirectoryExtPath(pid, path, nameBuffer);
            }
        }
    }

    /**
     * 目录根组
     *
     * @return AInfoType
     */
    public static AInfoDirectory getRootDirectory() {
        AInfoDirectory adirec = new AInfoDirectoryImpl();
        Map info = new HashMap();
        info.put("ID_ID", "0");
        info.put("ID_NAME", "专题&栏目");
        info.put("ID_MEMO", "专题/栏目树状结构根节点");
        info.put("ID_KEY", "root");
        info.put("ID_TEMP", "");
        info.put("ID_PARENT", "-1");
        info.put("HASCHILD", "true");
        info.put("ID_USERID", "");
        info.put("ID_USERNAME", "");
        info.put("ID_DATE", "");
        info.put("ID_ORDER", "");
        info.put("EXT_DPATH", "/-1/0");

        adirec.reload(info);

        return adirec;
    }

    /**
     * 默认的无权访问栏目
     *
     * @return AInfoDirectory
     */
    public static AInfoDirectory getFakeDirectory() {
        AInfoDirectory adirec = new AInfoDirectoryImpl();
        Map info = new HashMap();
        info.put("ID_ID", "-1");
        info.put("ID_NAME", "无权访问");
        info.put("ID_MEMO", "无权访问专题/栏目");
        info.put("ID_KEY", "noright");
        info.put("ID_TEMP", "");
        info.put("ID_PARENT", "-1");
        info.put("HASCHILD", "true");
        info.put("ID_USERID", "");
        info.put("ID_USERNAME", "");
        info.put("ID_DATE", "");
        info.put("ID_LABELIMGURL", context + "/app/info/images/noright.gif");
        info.put("ID_TITLEIMGURL", context + "/app/info/images/noright.gif");
        info.put("ID_ORDER", "");

        adirec.reload(info);

        return adirec;
    }

    /**
     * 不存在的栏目信息
     *
     * @return
     */
    public static AInfoDirectory getVirtualDirectory() {
        AInfoDirectory adirec = new AInfoDirectoryImpl();
        Map info = new HashMap();
        info.put("ID_ID", "-1");
        info.put("ID_NAME", "无效的专题/栏目");
        info.put("ID_MEMO", "无效的专题/栏目");
        info.put("ID_KEY", "notfound");
        info.put("ID_TEMP", "");
        info.put("ID_PARENT", "-1");
        info.put("HASCHILD", "true");
        info.put("ID_USERID", "");
        info.put("ID_USERNAME", "");
        info.put("ID_DATE", "");
        info.put("ID_LABELIMGURL", context + "/app/info/images/notfound.gif");
        info.put("ID_TITLEIMGURL", context + "/app/info/images/notfound.gif");
        info.put("ID_ORDER", "");

        adirec.reload(info);

        return adirec;
    }

    /**
     * 目录信息列表(系统首页)
     *
     * @param user
     *            当前用户
     * @param key
     *            目录key
     * @param size
     *            信息数量
     * @return List
     */
    public List getIssueAInfoInDirectory(IUser user, String key, int size) {
        AInfoDirectory direc = this.getAInfoDirectoryByKey(key);

        if (direc == null) {
            direc = this.getAInfoDirectoryById(key);
        }

        List list = null;

        if (direc != null) {
            StringBuffer where = new StringBuffer(" AND ID_ID = " + direc.id());

            String lumeid = user.iallgroupflumeid(",");

            lumeid = UserManager.iallgroupflumeid(lumeid);

            where.append(
                " AND APP_INFO_ISSUE.IS_OBJ_TYPE = 'info' and APP_INFO_ISSUE.IS_AREAID in (" +
                (lumeid.equals("") ? "-1" : lumeid) + ")");

            String sql =
                "SELECT APP_INFO.* FROM APP_INFO WHERE IF_ID IN (SELECT APP_INFO.IF_ID FROM APP_INFO," +
                "APP_INFO_ISSUE WHERE APP_INFO.IF_ID = " +
                "APP_INFO_ISSUE.IS_OBJ_ID AND IF_DEL = 0 AND IF_STATUS = 1 " +
                where.toString() +
                " GROUP BY APP_INFO.IF_ID) ORDER BY IF_TOP DESC, IF_DATE DESC";

            if (size > 0) {
                list = this.trimmer.searchMultiData(sql, size);
            } else {
                list = this.trimmer.searchMultiData(sql);
            }
        } else {
            System.err.println("not found directory '" + key + "'");
        }

        return list;
    }

    /**
     * 类别信息列表(系统首页�?)
     *
     * @param user
     *            当前用户
     * @param key
     *            目录key
     * @param size
     *            信息数量
     * @return List
     */
    public List getIssueAInfoInType(IUser user, String key, int size) {
        List list = null;
        XWordbookMain wbmain = XWordbookMain.getInstance();
        XWordbookQuery query = wbmain.getWordbookQuery("info-type");

        if (query != null) {
            XWordbook wb = query.query(key);

            if (wb != null) {
                StringBuffer where = new StringBuffer(" AND IT_ID = " +
                        wb.getID());

                IGroup group = user.igroup();

                if (group != null) {
                    String lumeid = UserManager.iallgroupflumeid(user.iallgroupflumeid(
                                ","));

                    where.append(
                        " AND APP_INFO_ISSUE.IS_OBJ_TYPE = 'info' and APP_INFO_ISSUE.IS_AREAID in (" +
                        (lumeid.equals("") ? "-1" : lumeid) + ")");
                }

                String sql =
                    "SELECT APP_INFO.* FROM APP_INFO WHERE IF_ID IN (SELECT APP_INFO.IF_ID FROM APP_INFO," +
                    "APP_INFO_ISSUE WHERE APP_INFO.IF_ID = " +
                    "APP_INFO_ISSUE.IS_OBJ_ID AND IF_DEL = 0 " +
                    where.toString() +
                    " GROUP BY APP_INFO.IF_ID) ORDER BY IF_DATE DESC";

                list = this.trimmer.searchMultiData(sql, size);
            } else {
                System.err.println("not found type '" + key + "'");
            }
        } else {
            System.err.println("not found type in workbook 'info-type'");
        }

        return list;
    }

    /**
     * 个人查看记录
     *
     * @param type
     * @param userid
     * @return
     */
    public Map getTraceMap(String userid) {
        String sql = "SELECT * FROM APP_INFO_RECEIPT WHERE USER_ID = " +
            userid;

        Map info = this.trimmer.searchSymmetricalMap(sql, "AF_ID");

        return info;
    }

    /**
     * 初始化内容预览信息实例
     *
     * @param bean
     * @return
     */
    public static AInfo getAInfo4Preview(CommonBean4HSQ bean, IUser user) {
        AInfo info = new AInfoImpl();
        Map para = bean.getResource();

        TableRegisterCenter center = TableRegisterCenter.getInstance();

        Table table = center.findTable("APP_INFO");

        List columns = table.columns();

        Map temp = new HashMap();

        for (int i = 0; i < columns.size(); i++) {
            Column column = (Column) columns.get(i);
            temp.put(column.getName(),
                StringTool.checkString(para.get(column.getFormName())));
        }

        if (table.hasAnnex()) {
            if (para.containsKey(AnnexItem.ANNEX)) {
                AnnexItem item = (AnnexItem) para.get(AnnexItem.ANNEX);
                Map annexInfo = (Map) item.getResource().get(AnnexItem.ANNEX);
                List list = new ArrayList();
                Iterator iter = annexInfo.keySet().iterator();

                while (iter.hasNext()) {
                    String key = (String) iter.next();
                    AttFileItem fileitem = (AttFileItem) annexInfo.get(key);
                    list.add(new String[] { "", fileitem.getFileFactName() });
                }

                temp.put("ANNEXS", list);
            }
        }

        temp.put("USER", user);

        info.reload(temp);

        return info;
    }

    /**
     * 栏目信息列表
     *
     * @param key
     * @param user
     * @param pageSize
     * @return
     */
    public List listInfo(String id, IUser user, String pageSize) {
        Connection conn = null;
        List resultList = null;

        int size = 10;

        try {
            size = Integer.parseInt(pageSize);
        } catch (Exception ex) {
            // do nothing
        }

        StringBuffer where = new StringBuffer(" AND IF_DEL = 0 ");

        where.append(" AND ID_ID = " + id);

        String lumeid = UserManager.iallgroupflumeid(user.iallgroupflumeid(","));

        where.append(
            " AND APP_INFO_ISSUE.IS_OBJ_TYPE = 'info' and APP_INFO_ISSUE.IS_AREAID in (" +
            (lumeid.equals("") ? "-1" : lumeid) + ")");

        String sql =
            "SELECT APP_INFO.* FROM APP_INFO WHERE IF_ID IN (SELECT APP_INFO.IF_ID FROM APP_INFO," +
            "APP_INFO_ISSUE WHERE APP_INFO.IF_ID = " +
            "APP_INFO_ISSUE.IS_OBJ_ID " + where.toString() +
            " GROUP BY APP_INFO.IF_ID) ORDER BY IF_DATE DESC";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            DataTrimmer trimmer = new DataTrimmer(conn);

            resultList = trimmer.searchMultiData(sql, size);
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return resultList;
    }

    /**
     * 栏目信息列表
     *
     * @param key
     * @param user
     * @param pageSize
     * @param curPage
     * @return Object[]{信息list,数据总计,页数总计}
     */
    public Object[] listInfo(String id, IUser user, String pageSize,
        String curPage) {
        Connection conn = null;
        List resultList = null;

        Object[] obj = null;

        StringBuffer where = new StringBuffer(" AND IF_DEL = 0 ");

        where.append(" AND ID_ID = " + id);

        String lumeid = UserManager.iallgroupflumeid(user.iallgroupflumeid(","));

        where.append(
            " AND APP_INFO_ISSUE.IS_OBJ_TYPE = 'info' and APP_INFO_ISSUE.IS_AREAID in (" +
            (lumeid.equals("") ? "-1" : lumeid) + ")");

        String sql1 =
            "SELECT COUNT(APP_INFO.IF_ID) FROM APP_INFO WHERE IF_ID IN (SELECT APP_INFO.IF_ID FROM APP_INFO," +
            "APP_INFO_ISSUE WHERE APP_INFO.IF_ID = " +
            "APP_INFO_ISSUE.IS_OBJ_ID " + where.toString() +
            " GROUP BY APP_INFO.IF_ID) ";

        String sql2 =
            "SELECT APP_INFO.* FROM APP_INFO WHERE IF_ID IN (SELECT APP_INFO.IF_ID FROM APP_INFO," +
            "APP_INFO_ISSUE WHERE APP_INFO.IF_ID = " +
            "APP_INFO_ISSUE.IS_OBJ_ID " + where.toString() +
            " GROUP BY APP_INFO.IF_ID) ORDER BY IF_DATE DESC";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, "");
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, pageSize);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, curPage);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            resultList = plus.work();

            obj = new Object[] {
                    resultList, String.valueOf(""), String.valueOf("")
                };
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return obj;
    }

    /**
     * 获得信息�?属专�?
     *
     * @param id
     *            信息ID
     * @return AInfoDirectory
     */
    public AInfoDirectory getAInfoSubjectById(String id) {
        AInfoDirectory direc = this.getAInfoDirectoryById(id);

        if (direc.iparentid().equals("0")) {
            return direc;
        } else {
            return getAInfoSubjectById(direc.iparentid());
        }
    }

    /**
     * 根据幻灯片KEY得到幻灯片内�?
     *
     * @param key
     * @return
     */
    public List getSlideInfoByKey(String key) throws ISystemException {
        List list = null;

        String sql = "SELECT * FROM APP_INFO_SLIDE WHERE ASKEY = '" + key +
            "'";
        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            String id = (String) info.get("AS_ID");

            sql = "SELECT APP_INFO_SLIDEITEM.ASI_ID,APP_INFO.IF_ID,APP_INFO.IF_TITLE " +
                "FROM APP_INFO_SLIDEITEM LEFT JOIN APP_INFO ON APP_INFO_SLIDEITEM.AF_ID = " +
                "APP_INFO.IF_ID WHERE AS_ID = " + id;

            list = this.trimmer.searchMultiData(sql);

            if ((list != null) && !list.isEmpty()) {
                AnnexTool annex = new AnnexTool(this.conn);

                for (int i = 0; i < list.size(); i++) {
                    Map temp = (Map) list.get(i);
                    String asiid = (String) temp.get("ASI_ID");
                    String title = (String) temp.get("IF_TITLE");
                    ((Map) list.get(i)).put("IF_TITLE",
                        HTMLTool.htmlEscape(title));

                    AnnexInfo[] annexs = annex.getAnnexs(asiid,
                            "APP_INFO_SLIDEITEM");

                    if ((annexs != null) && (annexs.length > 0)) {
                        try {
                            AnnexInfo newannexinfo = annex.cloneAnnex(annexs[0].getID());
                            temp.put("IMG_URL", newannexinfo.getLinkString());
                        } catch (Exception ex) {
                            temp.put("IMG_URL", "");
                            ISystem.catchException(this, ex);
                        }
                    } else {
                        temp.put("IMG_URL", "");
                    }
                }
            }
        } else {
            throw new ISystemException("没有定义幻灯片['" + key + "'].");
        }

        return list;
    }

    /**
     * 根据幻灯片KEY得到幻灯片内�?
     *
     * @param key
     * @return
     */
    public Map getSlideInfoById(String id) {
        String sql = "SELECT * FROM APP_INFO_SLIDE WHERE AS_ID = " + id;
        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            sql = "SELECT APP_INFO_SLIDEITEM.ASI_ID,APP_INFO.IF_ID,APP_INFO.IF_TITLE " +
                "FROM APP_INFO_SLIDEITEM LEFT JOIN APP_INFO ON APP_INFO_SLIDEITEM.AF_ID = " +
                "APP_INFO.IF_ID WHERE AS_ID = " + id;

            List list = this.trimmer.searchMultiData(sql);

            if ((list != null) && !list.isEmpty()) {
                AnnexTool annex = new AnnexTool(this.conn);

                for (int i = 0; i < list.size(); i++) {
                    Map temp = (Map) list.get(i);
                    String asiid = (String) temp.get("ASI_ID");
                    String title = (String) temp.get("IF_TITLE");
                    ((Map) list.get(i)).put("IF_TITLE",
                        HTMLTool.htmlEscape(title));

                    AnnexInfo[] annexs = annex.getAnnexs(asiid,
                            "APP_INFO_SLIDEITEM");

                    if ((annexs != null) && (annexs.length > 0)) {
                        try {
                            AnnexInfo newannexinfo = annex.cloneAnnex(annexs[0].getID());
                            temp.put("IMG_ID", newannexinfo.getID());
                            temp.put("IMG_URL", newannexinfo.getLinkString());
                        } catch (Exception ex) {
                            temp.put("IMG_ID", "");
                            temp.put("IMG_URL", "");
                            ISystem.catchException(this, ex);
                        }
                    } else {
                        temp.put("IMG_URL", "");
                    }
                }
            }

            info.put("ITEMS", list);
        }

        return info;
    }

    /**
     * 删除幻灯片新闻项
     *
     * @param id
     *            幻灯片新闻项id
     * @throws ISystemException
     */
    public void delslideitem(String id) throws ISystemException {
        String sql = "DELETE FROM APP_INFO_SLIDEITEM WHERE ASI_ID = " + id;

        if (this.trimmer.execute(sql)) {
            AnnexTool annex = new AnnexTool(conn);

            try {
                annex.deleteAnnex(id, "APP_INFO_SLIDEITEM");
            } catch (Exception ex) {
                throw new ISystemException("delete slide item error.", ex);
            }
        } else {
            throw new ISystemException("delete slide item error.");
        }
    }

    /**
     * 删除幻灯片新闻
     *
     * @param id
     *            幻灯片新闻ID
     * @throws ISystemException
     */
    public void delslide(String id) throws ISystemException {
        String sql = "DELETE FROM APP_INFO_SLIDE WHERE AS_ID = " + id;

        if (this.trimmer.execute(sql)) {
            sql = "SELECT * FROM APP_INFO_SLIDEITEM WHERE AS_ID = " + id;

            List list = this.trimmer.searchMultiData(sql);

            if ((list != null) && !list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    Map info = (Map) list.get(i);
                    String itemid = (String) info.get("ASI_ID");
                    this.delslideitem(itemid);
                }
            }
        } else {
            throw new ISystemException("delete slide error.");
        }
    }

    /**
     * 清除内容信息中上传的图片文件
     *
     * @param id 内容信息ID
     * @throws ISystemException
     */
    public void cleanResourcesInInfo(String id) throws ISystemException {
        AnnexTool tool = new AnnexTool(conn);

        AnnexInfo[] annexs = tool.getAnnexs(id, "INSERT_IMG");

        if ((annexs != null) && (annexs.length > 0)) {
            String realPath = StringTool.checkString(XSystemConfig.config()
                                                                  .getProperty(XSystemConfig.XSYSTEM_REALPATH));

            for (int i = 0; i < annexs.length; i++) {
                AnnexInfo annexInfo = annexs[i];

                try {
                    File tempRoot = new File(new File(realPath, "temp-store"),
                            annexInfo.getRepository());

                    String fileName = annexInfo.getTrueName();

                    String fileType = StringTool.checkString(annexInfo.getType());

                    if (!fileType.equals("")) {
                        fileName += ("." + annexInfo.getType());
                    }

                    File tempfile = new File(tempRoot, fileName);

                    if (tempfile.exists()) {
                        tempfile.delete();
                    }

                    tool.deleteAnnex(annexInfo.getID());
                } catch (Exception ex) {
                    throw new ISystemException("clean resources from info error.",
                        ex);
                }
            }
        }
    }

    /**
     * 删除信息内容中插入的图片
     *
     * @param url 图片url
     */
    public boolean cleanImageInInfo(String url) {
        boolean rnt = false;

        String imgServer = StringTool.checkString(XSystemConfig.config()
                                                               .getProperty("IMAGE_SERVER"),
                "-1");

        if (url.startsWith(imgServer)) {
            String id = url.substring(url.lastIndexOf("/") + 1, url.indexOf("."));

            AnnexTool tool = new AnnexTool(conn);

            try {
                tool.deleteAnnex(id);

                String realPath = StringTool.checkString(XSystemConfig.config()
                                                                      .getProperty(XSystemConfig.XSYSTEM_REALPATH));

                File file = new File(realPath, url.substring(imgServer.length()));

                if (file.exists()) {
                    file.delete();
                }

                rnt = true;
            } catch (Exception ex) {
                ISystem.catchException(ex);
            }
        }

        return rnt;
    }

    /**
     * 更新新闻图片外键ID
     *
     * @param id 新闻信息新ID
     * @param uniqueid 原外键ID
     */
    public void updateImageInInfo(String id, String uniqueid) {
        String sql = "UPDATE XSYSTEM_ANNEX SET FK_ANNEX_ID = " + id +
            " WHERE FK_ANNEX_ID = '" + uniqueid + "'";

        this.trimmer.execute(sql);
    }

    /**
     * 更新有效回复人数
     * @param id 信息ID
     * @param n 增加数量
     */
    public void updateReplyCount(String id, int n) {
        String sql = "SELECT IF_RECOUNT FROM APP_INFO WHERE IF_ID = " + id;

        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            int o = Integer.parseInt((String) info.get("IF_RECOUNT"));

            if ((o == 0) && (n < 0)) {
                //do nothing
            } else {
                int r = Integer.parseInt((String) info.get("IF_RECOUNT")) + n;

                sql = "UPDATE APP_INFO SET IF_RECOUNT = " + r +
                    " WHERE IF_ID = " + id;

                this.trimmer.execute(sql);
            }
        }
    }

    /**
     * 更新参与人数
     * @param id 信息ID
     */
    public void updateInvolvementCount(String id) {
        String sql = "SELECT IF_IVCOUNT FROM APP_INFO WHERE IF_ID = " + id;

        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            int r = Integer.parseInt((String) info.get("IF_IVCOUNT")) + 1;

            sql = "UPDATE APP_INFO SET IF_IVCOUNT = " + r + " WHERE IF_ID = " +
                id;

            this.trimmer.execute(sql);
        }
    }

    /**
     * 更新浏览总数
     * @param id 信息ID
     */
    public void updateViewCount(String id) {
        String sql = "SELECT IF_VECOUNT FROM APP_INFO WHERE IF_ID = " + id;

        Map info = this.trimmer.searchSingleData(sql);

        if (info != null) {
            int r = Integer.parseInt((String) info.get("IF_VECOUNT")) + 1;

            sql = "UPDATE APP_INFO SET IF_VECOUNT = " + r + " WHERE IF_ID = " +
                id;

            this.trimmer.execute(sql);
        }
    }
}
